﻿$(function(){
		function CalculatedPrice(row, btn, discount, num, each, cost){
			
			$('#'+btn+'>p>a').click(function(){
				var listplength = $('#'+btn+'>p').length;
				if(listplength > 1){
					$(this).parent('p').remove();
					var newlistplength = $('#'+btn+'>p').length;
					var _discount = parseInt($('#'+discount).html()) / 10;
					$('#'+num).html(newlistplength);
					var _each = parseInt($('#'+each).html());
					var _cost = newlistplength * _each;
					$('#'+cost).html(_cost);
				}else{
					$('#'+row).remove();
				}
				var allcosts = getPrice();
				
				$('#allcost').html(allcosts);

				var alloriginals = cheaperthan();
				
				$('#cheaper').html(alloriginals);
			});
			function getPrice(){
				var cost1 = parseInt($('#cost1').html()) ? parseInt($('#cost1').html()) : 0;
				var cost2 = parseInt($('#cost2').html()) ? parseInt($('#cost2').html()) : 0;
				var cost3 = parseInt($('#cost3').html()) ? parseInt($('#cost3').html()) : 0;
				var cost4 = parseInt($('#cost4').html()) ? parseInt($('#cost4').html()) : 0;
				var allcost = cost1 + cost2 + cost3 + cost4;
				return allcost;
			}
			function cheaperthan(){
				var original1 = parseInt($('#cost1').html()) ? (parseInt($('#cost1').html()) / (parseInt($('#discount1').html()) / 10)) : 0;
				var original2 = parseInt($('#cost2').html()) ? (parseInt($('#cost2').html()) / (parseInt($('#discount2').html()) / 10)) : 0;
				var original3 = parseInt($('#cost3').html()) ? (parseInt($('#cost3').html()) / (parseInt($('#discount3').html()) / 10)) : 0;
				var original4 = parseInt($('#cost4').html()) ? (parseInt($('#cost4').html()) / (parseInt($('#discount4').html()) / 10)) : 0;
				console.log(original1);
				var alloriginal = original1 + original2 + original3 + original4 - parseInt($('#allcost').html());
				return alloriginal;
			}
		};

		CalculatedPrice('row1', 'listp1', 'discount1', 'num1', 'each1', 'cost1');
		CalculatedPrice('row2', 'listp2', 'discount2', 'num2', 'each2', 'cost2');
		CalculatedPrice('row3', 'listp3', 'discount3', 'num3', 'each3', 'cost3');
		CalculatedPrice('row4', 'listp4', 'discount4', 'num4', 'each4', 'cost4');
	})